using System;
using System.Configuration;
using System.Net.Mail;
using System.Threading;

namespace KickStart.Data.Mail
{
    public class MailerService : IMailerService
    {
        private readonly string FromEmail = ConfigurationManager.AppSettings["fromemail"];
        public static ILogger Logger
        {
            get;
            set;
        }

        public MailerService()
        {
            Logger = new NullLogger();
        }


        public void Send(MailMessage message)
        {
            try
            {
#if DEBUG
                try
                {
                    Console.WriteLine("Mail To: " + message.To[0].Address);
                    Console.WriteLine("Subject: " + message.Subject);
                    Console.WriteLine("Body: \r\n" + message.Body);
                }
                catch (Exception e)
                {
                    Logger.Error(e);
                }
#endif
                if (message.From == null)
                {
                    //get the admin email and name first
                    _adminEmail = FromEmail;
                    _adminName = FromEmail;
                }
                var t1 = new Thread(SendMailAsync);
                t1.Start(message);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }



        private static string _adminEmail;
        private static string _adminName;


        private void SendMailAsync(object emailInfo)
        {
            try
            {
                var mailMessage = emailInfo as MailMessage;
                if (mailMessage != null)
                {

                    if (mailMessage.From == null)
                        mailMessage.From = new MailAddress(_adminEmail,
                                                           _adminName);
                    mailMessage.IsBodyHtml = false;

                    var mailClient = new SmtpClient();
                    mailClient.Send(mailMessage);

                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
    }
}